const jwt = require('jsonwebtoken');
const omit = require('lodash/omit')
const { staff_collection } = require('../config')
const { db } = require('../config')
const { command } = require('../config')
const _ = command
const common = require('./common');
exports.main = async (event, context) => {
  const { secret } = event,
    { account, password } = event.data;
  const GET = await db.collection(staff_collection)
    .where({
      account: account,
      status: _.neq('离职')
    })
    .get();
  if (!GET.data.length) return { state: 'noPass', msg: '用户名或密码错误或账号不存在' };

  const STAFF = GET.data[0];

  // const isMatch = bcrypt.compareSync(password, STAFF.password);

  let isMatch = password === STAFF.password;
  if (isMatch) {
    var userInfo = common.simplePosition(STAFF);
    const token = jwt.sign({ account: userInfo.account, name: userInfo.name, password: userInfo.password }, 'shhhhh', { expiresIn: '1h' });
    userInfo = {
      name: userInfo.name,
      account: userInfo.account,
      id: userInfo.id,
      phone: userInfo.phone,
      status: userInfo.status,
      region: userInfo.region,
      grid: userInfo.grid,
      position: userInfo.position,
    }
    return { state: 'pass', msg: '登录成功', data: userInfo, token };
  } else {
    return { state: 'noPass', msg: '用户名或密码错误' };
  }
}